import { defineStore } from "pinia";
import { studentLoginApi } from "@/http/Api/students/userApi";
import { teacherLoginApi } from "@/http/Api/teachers/userApi";
import type { LoginProps } from "@/http/Api/type";
import studentsRoutes from "@/router/studentsRoutes";
import teachersRoutes from "@/router/teachersRoutes";
// import { AddDynamicList } from "@/router/permission";
import router from "@/router/index";

export const useStore = defineStore("main", {
  state: () => {
    return {
      user: JSON.parse(sessionStorage.getItem("user") || "{}"),
      token: sessionStorage.getItem("token"),
      roleList: JSON.parse(sessionStorage.getItem("roleList") || "[]"),
      asyncRoutestMark: false, // 标记是否已经添加路由
      systemName: "百杰小助手系统",
    };
  },
  getters: {},
  actions: {
    setAsyncRoutestMark(mark: boolean) {
      this.asyncRoutestMark = mark;
    },
    async studentLoginAction(params: LoginProps) {
      try {
        const userData = await studentLoginApi(params);
        console.log("学生用户登录信息：", userData.data);

        if (userData.data.code != "200") {
          return Promise.reject(userData.data.msg);
        }

        const user = {
          departmentId: userData.data.data.baiJieClassId,
          departmentName: userData.data.data.baiJieName,
          headPortrait: userData.data.data.headPortrait,
          userId: userData.data.data.id,
          lastLoginTime: userData.data.data.lastLoginTime,
          nickname: userData.data.data.nickname,
          phone: userData.data.data.phone,
          sex: userData.data.data.sex,
          username: userData.data.data.username,
        };

        sessionStorage.setItem("user", JSON.stringify(user));

        sessionStorage.setItem("token", "token");
        sessionStorage.setItem("roleList", JSON.stringify(studentsRoutes));
        sessionStorage.setItem("defaultActive", "/");

        this.user = user;
        this.token = "token";
        this.roleList = studentsRoutes;
      } catch (e) {
        console.log("登录错误：", e);
        return Promise.reject("登录错误");
      }
    },
    async teacherLoginAction(params: LoginProps) {
      try {
        const userData = await teacherLoginApi(params);
        // console.log("管理员用户登录信息：", userData.data);

        if (userData.data.code != "200") {
          return Promise.reject(userData.data.msg);
        }

        const user = {
          departmentId: userData.data.data.baiJieClassId,
          departmentName: userData.data.data.baiJieName,
          headPortrait: userData.data.data.headPortrait,
          userId: userData.data.data.id,
          lastLoginTime: userData.data.data.lastLoginTime,
          nickname: userData.data.data.nickname,
          phone: userData.data.data.phone,
          sex: userData.data.data.sex,
          username: userData.data.data.username,
        };

        sessionStorage.setItem("user", JSON.stringify(user));

        sessionStorage.setItem("token", "token");
        sessionStorage.setItem("roleList", JSON.stringify(teachersRoutes));
        sessionStorage.setItem("defaultActive", "/");

        this.user = user;
        this.token = "token";
        this.roleList = teachersRoutes;
      } catch (err) {
        console.log("登录错误：", err);
        return Promise.reject("登录错误");
      }
    },
    quitSystemAction() {
      removeDynamicRoute(this.roleList);

      this.user = {};
      this.token = "";
      this.roleList = [];
      this.asyncRoutestMark = false;

      sessionStorage.clear();
      return Promise.resolve();
    },
  },
});

function removeDynamicRoute(routes: Array<any>) {
  for (let i = 0; i < routes.length; i++) {
    if (routes[i].name) {
      router.removeRoute(routes[i].name);
    }

    if (routes[i].children && routes[i].children.length > 0) {
      removeDynamicRoute(routes[i].children);
    }
  }
}
